#include "server.h"

int flag=1;

TCP_fd TCP_init(char *port_num, char *IP_addr,TCP_fd fd)
{
   
    fd.soc_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (-1 == fd.soc_fd)
    {
        ERRLOG("socket error");
        return fd;
    }
    struct sockaddr_in soc_addr_in;
    soc_addr_in.sin_family = AF_INET;
    soc_addr_in.sin_port = htons((uint16_t)atoi(*port_num)); // 端口号
    soc_addr_in.sin_addr.s_addr = inet_addr(*IP_addr);       // ip地址
    socklen_t addrlen = sizeof(soc_addr_in);

    // 绑定
    if (-1 == bind(fd.soc_fd, (struct sockaddr *)&soc_addr_in, addrlen))
    {
        ERRLOG("bind error");
        return fd;
    }
    // 将套接字设置城 监听状态
    if (-1 == listen(fd.soc_fd, 3))
    {
        ERRLOG(" listen error:");
        return fd;
    }

    // ​ 阻塞等待客户端连接 accept
    system("clear");
    printf("服务器等待连接\n");
    fd.soc_fd = accept(fd.soc_fd, NULL, NULL);
    if (fd.soc_fd == -1)
    {
        ERRLOG(" accept error:");
        return fd;
    }
    printf("服务器连接成功\n");

    return fd;
}
// 数据接收
void* rece_pack(void* acc_fd)
{
    char receive_buf[128];

    while (flag)
    {

        memset(receive_buf, 0, sizeof(receive_buf));

        if (read(*(int *)acc_fd, receive_buf, sizeof(receive_buf)) <= 0)
        {
            continue;
        }
        printf("对方回复：%s \n", receive_buf);
        if (!strcmp(receive_buf, "quit"))
        {
            flag=0;
            printf("接收端退出连接\n");
            break;
        }
    }

}

// 数据发送
void* send_pack(void* acc_fd)
{
    char transmit_buf[128];
    while (flag)
    {

        memset(transmit_buf, 0, sizeof(transmit_buf));
        scanf("%s", transmit_buf);
        write(*(int *)acc_fd, transmit_buf, strlen(transmit_buf));
        if (!strcmp(transmit_buf, "quit"))
        {
            flag=0;
            printf("发送端退出连接\n");
            break;
        }
    }

}


//多线程
int thread_send_rece(int acc_fd)
{
    pthread_t rece_tid, send_tid;
    if (0 != pthread_create(&rece_tid, NULL, rece_pack, (void *)&acc_fd))
    {
        ERRLOG("rece_tid pthread_create error:");
        return 1;
    }
    if (0 != pthread_create(&send_tid, NULL, send_pack, (void *)&acc_fd))
    {
        ERRLOG("send pthread_create error:");
        return 1;
    }
    pthread_join(send_tid,NULL);
    pthread_join(rece_tid,NULL);
    return 0;
}

void TCP_close(TCP_fd fd)
{
    close(fd.soc_fd);
    close(fd.acc_fd);
    
}
